#! /usr/bin/python

from __future__ import division
import logging

logger = logging.getLogger()
f = open('randcontacts.txt')
o = open('randout.txt','w')
u={}
cb={}
def init_relation():
    for i in f:
        j = i[:-1].split(',')
        if u.get(j[0]) is None:
            u[j[0]] = {'like':[], 'likedby':[], 'id':j[0]}
        if u.get(j[1]) is None:
            u[j[1]] = {'like':[], 'likedby':[], 'id':j[1]}
        u[j[0]]['like'].append(j[1])
        u[j[1]]['likedby'].append(j[0])
    logger.info('init done')

def export_rank():
    h = [(u[i]['id'],len(set(u[i]['likedby']+u[i]['like']))) for i in u]
    y = sorted(h,key=lambda d: d[1],reverse=True)

    yfile = open('randrank.txt','w')
    for i in y:
        yfile.write('%s : %s\n'%(i[0],i[1]))

    yfile.close()


def calc(n=None):
    lenu = len(u)
    for i,sid in enumerate(u):
        s = u[sid]
        logger.info('calc s: %s (%s/%s)'% (sid,i,lenu))
        if n and n<i:
            break
        sta = []
        p = {}
        sgm = {}
        sgm[sid] = 1
        d = {}
        d[sid] = 0
        q = []
        q.append(sid)
        try:
            while 1:
                v = q[0]
                q.remove(q[0])
                sta.append(v)
                for w in set(u[v]['like']):
                    if d.get(w) is None:
                        q.append(w)
                        d[w] = d[v] + 1

                    if d[w] == d[v] + 1:
                        sgm[w] = sgm.get(w,0) + sgm[v]
                        if p.get(w) is None:
                            p[w] = [v]
                        else:
                            p[w].append(v)
        except IndexError:
            pass


        delta = {}
   #     print 'stack:%s'%(sta)
        try:
            while 1:
                w = sta.pop()
   #             print 'pre of %s is %s' %(w,p.get(w,[]))
                for v in p.get(w,[]):
                    if delta.get(w) is None:
                        delta[w] = 0
                    delta[v] = delta.get(v,0) + sgm[v]/sgm[w] * (1+delta[w])
   #                 print 'delta[%s] is currently %s'%(v,delta[v])
   #                 print 'deltawww[%s] is currently %s'%(w,delta[w])
                if w != sid:
                    cb[w] = cb.get(w,0)+delta[w]
                    #print 'cb[%s] is currently adding %s' %(w,delta[w])
        except IndexError:
            pass

def print_bc():
    t = sorted(cb.items(),key=lambda d: d[1],reverse=True)
    for u in t:
        o.write('%s:%s\n' % (u[0], u[1]))
#        print '%s: %s' % (u[0], u[1])


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
            format='%(asctime)s %(levelname)-8s %(message)s',
            filename='nbclog.log',
            filemode='a')
    init_relation()
    export_rank()
#    calc()
#    print_bc()

